﻿@page "{id?}"
@model DotNetStar.TheKing.Web.Pages.Content.EditModel
@{
    ViewBag.Title = $"创作中心";
    Layout = "/Pages/Shared/_Layout-Clean.cshtml";
    var btnClass = "btn btn-light border";

    var categories = ViewData["CategorySelectItems"] as IEnumerable<SelectListItem>;

    var id = ViewContext.RouteData.Values["id"].To(0);
    var channel = Request.Query["channel"].ToString();
}

<div id="panel">
    <nav class="navbar navbar-expand-lg bg-light mb-1">
        <a class="navbar-brand" href="/">
            <img src="~/images/logo.png" />
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item">
                    <h2>
                        <template v-if="model.IsContent">
                            创作中心
                            <small class="text-muted">你也是一个作家</small>
                        </template>
                        <template v-if="model.IsAsk">
                            有问必答
                            <small class="text-muted">尊重别人就是尊重自己</small>
                        </template>
                        <template v-if="model.IsVideo">
                            自媒体视频
                            <small class="text-muted">秀出自己的另一面</small>
                        </template>
                    </h2>

                </li>
            </ul>
        </div>
    </nav>

    <div class="row">
        <div class="col">
            <div class="alert alert-warning text-center" v-if="model.IsDraft">
                <h5><i class="fa fa-info-circle"></i> 当前内容来自于草稿箱，仅自己可见。点击【发布帖子】后将对外可见。</h5>
            </div>
            <div class="form-group">
                <div class="row">
                    <div class="col-2" v-if="!model.IsAsk">
                        <select class="form-control form-control-lg" v-model="model.IsOriginal">
                            <option value="true">原创</option>
                            <option value="false">转载</option>
                        </select>
                    </div>
                    <div class="col">
                        <input type="text" class="form-control form-control-lg" v-model="model.Subject" placeholder="标题" maxlength="60" />
                    </div>
                    <div class="col-2">
                        <div class="btn-group">
                            <button type="button" data-toggle="modal" data-target="#publishModal" class="btn btn-danger btn-lg" title="发布"><i class="fa fa-check"></i> 发布{{model.ChannelText}}</button>

                            
                            <button v-if="!model.IsAsk" type="button" class="btn btn-dark btn-lg" title="保存" @@click="submit(true)"><i class="fa fa-save"></i></button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-group" v-if="!model.IsVideo">
                <div class="float-left">
                    <div class="btn-group">
                        <button type="button" class="@btnClass" onclick="newDoc()" title="写新帖子"><i class="far fa-file"></i></button>
                        <button type="button" class="@btnClass" onclick="insertEditor('# ')" title="插入H1"><i class="fa fa-heading"></i><sub><strong>1</strong></sub></button>
                        <button type="button" class="@btnClass" onclick="insertEditor('## ')" title="插入H2"><i class="fa fa-heading"></i><sub><strong>2</strong></sub></button>
                        <button type="button" class="@btnClass" onclick="insertEditor('### ')" title="插入H3"><i class="fa fa-heading"></i><sub><strong>3</strong></sub></button>
                        <button type="button" class="@btnClass" onclick="insertEditor('#### ')" title="插入H4"><i class="fa fa-heading"></i><sub><strong>4</strong></sub></button>

                        <button type="button" class="@btnClass" onclick="insertEditor('**','**')" title="粗体"><i class="fa fa-bold"></i></button>
                        <button type="button" class="@btnClass" onclick="insertEditor('*','*')" title="斜体"><i class="fa fa-italic"></i></button>
                        <button type="button" class="@btnClass" onclick="insertEditor('> ','\r\n')" title="插入引用"><i class="fa fa-quote-left"></i></button>
                        <button type="button" class="@btnClass" onclick="insertEditor('* ')" title="无序列表"><i class="fa fa-list-ul"></i></button>
                        <button type="button" class="@btnClass" onclick="insertEditor('\r\n----')" title="插入分割线">—</button>
                        <div class="btn-group">
                            <button type="button" data-toggle="dropdown" class="@btnClass dropdown-toggle" title="插入代码">
                                <i class="fa fa-code"></i>
                            </button>
                            <div class="dropdown-menu">
                                <a class="dropdown-item" href="javascript:insertCode('cs')">C#</a>
                                <a class="dropdown-item" href="javascript:insertCode('html')">HTML</a>
                                <a class="dropdown-item" href="javascript:insertCode('js')">Javascript</a>
                                <a class="dropdown-item" href="javascript:insertCode('sql')">SQL</a>
                                <a class="dropdown-item" href="javascript:insertCode('json')">JSON</a>
                                <a class="dropdown-item" href="javascript:insertCode('xml')">XML</a>
                                <a class="dropdown-item" href="javascript:insertCode('')">通用</a>
                            </div>
                        </div>
                        <button type="button" class="@btnClass" onclick="insertLink()" title="插入超链接"><i class="fa fa-link"></i></button>
                        <div class="btn-group">
                            <button type="button" class="@btnClass" title="插入图片" onclick="showUploadPanel(this)">
                                <i class="fa fa-image"></i>
                            </button>
                            @Html.Partial("_Edit_UploadImage")
                        </div>

                        <button type="button" class="@btnClass" onclick="mdExampleModal()" title="Markdown 语法帮助"><i class="fa fa-question-circle"></i></button>
                        <button type="button" class="@btnClass active" onclick="switchSeperator(this)" title="显示预览面板"><i class="fa fa-columns"></i></button>
                    </div>
                </div>
                <div class="float-right">

                    <span id="saveLocal" style="display:none" class="text-muted text-sm"><i class="fa fa-spin fa-spinner"></i> 临时保存中...</span>
                </div>
                <div class="clearfix"></div>
                <div class="row">

                    <div class="col-6" id="col-content">
                        <textarea id="Body" v-model="model.Body" placeholder="请使用 Markdown 语法" class="form-control" rows="30"></textarea>
                    </div>
                    <div id="preview" class="markdown-body col-6 border" style="padding:10px;word-break:break-all;word-wrap:break-word;max-width:50%;overflow-x:hidden;overflow-y:scroll">
                        {{model.Body}}
                    </div>
                </div>
            </div>
            <div class="form-group" v-if="model.IsVideo">
                <textarea v-model="model.Url" rows="5" class="form-control" placeholder="视频的iframe代码。不支持视频上传，请上传到视频网站，然后将iframe代码复制在这里"></textarea>
            </div>
        </div>
    </div>
    <div class="modal fade" tabindex="-1" role="dialog" id="publishModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">发布{{model.ChannelText}}</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <input type="text" v-model="inputTag" class="form-control col" placeholder="标签，回车确认" v-on:keyUp.enter.stop="enterTag()" />
                        <span class="badge badge-secondary mr-1" v-for="item in model.Tags">{{item}} &nbsp;<span v-on:click="removeTag(item)" title="移除" class="pointer">X</span></span>
                    </div>
                    <div class="form-group">
                        <div class="form-row">
                            <div class="input-group col-6">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">
                                        <template v-if="model.IsAsk">
                                            悬赏
                                        </template>
                                        <template v-else>
                                            售价
                                        </template>
                                    </span>
                                </div>

                                <input type="number" v-model="model.Cost" min="1" class="form-control text-center" v-if="model.IsAsk" />
                                <input type="number" v-model="model.Cost" min="0" placeholder="不填则免费" class="form-control text-center" v-if="!model.IsAsk" />

                                <div class="input-group-append">
                                    <span class="input-group-text">
                                        个金币
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="form-row">
                            <div class="col-2">选择分类：</div>
                            <div class="col-6">
                                <select class="form-control" v-model="model.CategoryId">
                                    <option v-bind:value="item.Id" v-for="item in categories">{{item.Name}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <template v-if="model.IsAsk">
                        <div class="form-group">
                            <label class="checkbox">
                                <input type="checkbox" v-model="model.OnlyInvateUser" /> 仅邀请用户可回答
                                <small class="text-muted">勾选此项则必须设置邀请用户</small>
                            </label>
                        </div>
                        <div class="form-group">
                            <div class="form-row">
                                <div class="col-2">邀请回答：</div>
                                <div class="col">
                                    <div style="position:relative">

                                        <input type="text" v-model="userNameFilter" class="form-control col" placeholder="输入昵称" v-on:keyUp.stop="getUsers()" />
                                        <div class="border w-100" style="position:absolute;top:30px;background-color:white" v-if="showInvitePanel">
                                            <div v-if="users.length==0" class="text-center p-3">
                                                暂无任何数据！
                                            </div>
                                            <ul class="list-group" v-if="users.length>0">
                                                <li class="list-group-item pointer" onmouseout="$(this).removeClass('bg-primary text-white')" onmouseover="$(this).addClass('bg-primary text-white')" v-for="user in users" v-on:click="selectInvateUser(user)">
                                                    <img src="{{user.AvatarUrl}}" class="img-avatar-16" /> {{user.UserName}}
                                                    <template v-if="!user.NoInvite">
                                                        <small v-if="user.InviteCost">邀请身价：<i class="fa fa-database text-golden"></i> {{user.InviteCost}}</small>

                                                    </template>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                    <span class="badge badge-info mr-1" v-for="item in selectInviteUsers">
                                        <img src="{{item.AvatarUrl}}" class="img-avatar-16" />
                                        {{item.UserName}}
                                        <template v-if="!item.NoInvite">
                                            <small v-if="item.InviteCost"><i class="fa fa-database text-golden"></i> {{item.InviteCost}}</small>
                                        </template>
                                        &nbsp;
                                        <span v-on:click="removeInviteUser(item)" title="移除" class="pointer">X</span>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </template>


                    <div class="form-group" v-if="model.IsContent">
                        <label class="checkbox">
                            <input type="checkbox" v-model="model.IsSecret" title="仅自己可见" /> 设为私密帖子
                        </label>
                    </div>
                </div>
                <div class="modal-footer">
                    <span v-if="errorMsg" class="text-danger">{{errorMsg}}</span>
                    
                    <button type="button" class=" btn btn-outline-dark" v-on:click="submit(true)" v-if="!model.IsAsk"><i class="fa fa-save"></i> 存为草稿</button>
                    <button type="button" class="btn btn-danger w-25" v-on:click="submit(false)"><i class="fa fa-check"></i> 提 交</button>

                </div>
            </div>
        </div>
    </div>
</div>

@section styles{
    <link href="~/lib/webuploader/webuploader.css" rel="stylesheet" />
    <link href="~/js/highlight/vs.css" rel="stylesheet" />
    <link href="https://cdn.bootcss.com/codemirror/5.34.0/codemirror.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/highlight.js/9.12.0/styles/vs.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/codemirror/5.34.0/addon/hint/show-hint.min.css" rel="stylesheet">
    <link href="https://cdn.bootcss.com/codemirror/5.34.0/addon/display/fullscreen.css" rel="stylesheet">
    <style type="text/css">
        .CodeMirror {
            background-color: #eee;
            height: auto;
            padding: 20px;
            font-size: 14px;
        }

        .CodeMirror-scroll {
            height: 500px;
            overflow-y: auto;
            overflow-x: auto;
        }
    </style>
}

@section scripts{
    <script src="https://cdn.bootcss.com/codemirror/5.34.0/codemirror.js"></script>
    <script src="https://cdn.bootcss.com/codemirror/5.34.0/addon/display/placeholder.js"></script>
    <script src="https://cdn.bootcss.com/codemirror/5.34.0/addon/display/fullscreen.js"></script>
    <script src="https://cdn.bootcss.com/codemirror/5.34.0/mode/markdown/markdown.js"></script>
    <script src="https://cdn.bootcss.com/marked/0.3.12/marked.js"></script>
    <script src="https://cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js"></script>
    <script src="~/js/markdown.js"></script>
    <script src="~/lib/webuploader/webuploader.js"></script>

    <script type="text/javascript">
        let contentId =@id;
        let channel='@channel';

        let editor;//编辑器对象，在 vue 中被初始化
        let editorInitialized = false;
        let editorTimeoutId;
        let attchmentBatchId = '@Model.AttachBatchId';
        
        /**
         * 同步滚动
         * codeMirror： 对象
         * event： 事件
         */
        function asyncScroll(codeMirror, event) {
            var scrollInfo = codeMirror.getScrollInfo();

            var top =  scrollInfo.top / scrollInfo.height;
            $('#preview').scrollTop(top);
            console.log(scrollInfo)
            console.log('top:' + top);

            console.log('preview-top:' + $('#preview').scrollTop());
        }

        var markedRender = new marked.Renderer();
        marked.setOptions({
            renderer: markedRender,
            gfm: true,
            tables: true,
            breaks: true,  // '>' 换行，回车换成 <br>
            pedantic: false,
            sanitize: true,
            smartLists: true,
            smartypants: false
        });

        function markedHandler(codeMirror, changes) {
            var value = codeMirror.getValue()
            $('.markdown-body').html(marked(value));
            $('.markdown-body pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });

            vm.$data.model.Body = value;
        }


        /**
         * 新文档
         */
        function newDoc() {
            bootbox.confirm('将清空当前所有内容，确定吗', function (result) {
                if (result) {
                    editor.setValue('');
                    vm.$data.model.Body = '';
                }
            })
        }


        /**
         * 切换列
         * btn: 当前点击的按钮对象
         */
        function switchSeperator(btn) {
            var previewShown = $(btn).hasClass('active');//是否已经显示了预览面板
            if (previewShown) {
                $(btn).removeClass('active');
                $('#col-content').removeClass('col-6').addClass('col-12');
                $('.markdown-body').addClass('d-none');
            } else {
                $(btn).addClass('active');
                $('#col-content').addClass('col-6').removeClass('col-12');
                $('.markdown-body').removeClass('d-none');
            }
        }


       var vm= new Vue({
           el:'#panel',
            data: {
                model: @(Html.Raw(JsonConvert.SerializeObject(new EditContentViewModel { IsOriginal = false }))),
                
                categories: [],
                inputTag: '',
                errorMsg: null,
                files: [],
                userNameFilter: null,
                users: [],
                selectInviteUsers: [],
                showInvitePanel: false, //显示邀请用户的面板
            },
           mounted: function () {
               this.getData();

               editorTimeoutId = setInterval(initEditor, 200);

               
            },
            methods: {
                getData: function () {
                    let v = this;
                    $.ajax({
                        url: '@Url.Page("Edit","Content")',
                        data: { id: contentId, channel: channel },
                        type: 'get',
                        success: function (data) {
                            v.model = data;
                            v.selectInviteUsers = data.InvitedUsers;

                            v.getMainCategory();
                        }
                    })
                },
                getMainCategory: function () {
                    let v = this;
                    $.get('@Url.Page("Edit", "Category")', { pid: 0 }, function (data) {
                        v.categories = data;
                    });
                },
                submit: function (draft) {
                    let v = this;
                    if (!draft) {

                        if (!this.model.Subject) {
                            this.errorMsg = '请输入标题！';
                            return false;
                        }
                        if (!this.model.Body && !this.model.IsVideo) {
                            this.errorMsg='请输入正文！';
                            return false;
                        }
                        if (!this.model.CategoryId) {
                            this.errorMsg='请选择分类！';
                            return false;
                        }

                        if (this.model.OnlyInvateUser && this.selectInviteUsers.length == 0) {
                            this.errorMsg = '请设置邀请的用户！';
                            return false;
                        }

                    }
                    this.model.IsDraft = draft;

                    $.each(v.selectInviteUsers, function (i, item) {
                        v.model.InviteUserIds.push(item.Id);
                    })

                    var index = layer.load(2);
                    v.errorMsg = null;
                    $.ajax({
                        url: '@Url.Page("Edit")',
                        type: 'post',
                        data: v.model,
                        success: function (data) {
                            if (draft) {
                                $('#publishModal').modal('hide');
                                layer.msg('帖子已保存');
                            } else {
                                location.href = data;
                            }
                        },
                        error: function (data) {
                            $.alert(data.responseText);
                        },
                        complete: function () {
                            layer.close(index);
                        }
                    });
                },
                enterTag: function () {//输入标签的事件
                    let isRepeat = false
                    let v = this;
                    $.each(this.model.Tags, function (i, item) {
                        if (item == v.inputTag) {
                            isRepeat = true;
                            return;
                        }
                    })
                    if (!isRepeat && this.inputTag) {
                        this.model.Tags.push(this.inputTag);
                        this.inputTag = null;
                    }
                },
                removeTag: function (item) {
                    let index = this.model.Tags.indexOf(item);
                    this.model.Tags.splice(index, 1);
                },
                getUsers: function () {//填写了名称后查询用户
                    let v = this;

                    setTimeout(function () {
                        let index= layer.load(2);
                        $.getJSON('/api/users', { username: v.userNameFilter, top: 8 }, function (data) {
                            v.showInvitePanel = true;
                            v.users = data;
                            layer.close(index);
                        })
                    }, 1000);
                },
                selectInvateUser: function (user) {//从列表中选取一个用户
                    let isRepeat = false
                    let v = this;

                    v.showInvitePanel = false;

                    $.each(this.selectInviteUsers, function (i, item) {                        
                        if (item == v.user) {
                            isRepeat = true;
                            return;
                        }
                    })
                    if (!isRepeat) {

                        if (user.NoInvite) {
                            v.errorMsg = '该用户设置了"不允许被邀请"';
                            return;
                        }
                        if(user.Id==@(User.Identity.UserId())){
                            v.errorMsg = '不允许设置自己为邀请用户';
                            return;
                        }

                        this.selectInviteUsers.push(user);
                        this.userNameFilter = null;
                    }
                },
                removeInviteUser:function (user) {                    
                    let index = this.selectInviteUsers.indexOf(user);
                    this.selectInviteUsers.splice(index, 1);
                }
            }
        })





        function initEditor() {
            editor= CodeMirror.fromTextArea(document.getElementById('Body'), {
                    mode: 'markdown',
                    lineWrapping: true,
                    extraKeys: {
                        "Enter": "newlineAndIndentContinueMarkdownList",
                        "F11": function (cm) {
                            cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                        },
                        "Esc": function (cm) {
                            if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
                        }
                    }
            });
            if (editor) {
                $('.markdown-body').css({ 'height': $('.CodeMirror').outerHeight() + 'px' });
                editor.on('change', markedHandler);
                editor.on('scroll', function (instance) {
                    asyncScroll(instance);
                })
                //editor.on('scrollCursorIntoView', function (instance, event) {
                //    asyncScroll(instance, event);
                //});
                clearInterval(editorTimeoutId);

                if (vm.$data.model.Body) {
                    editor.setValue(vm.$data.model.Body);
                }
            }

            return editor;

        }

        let uploader = WebUploader.create({
            swf:'/lig/webuploader/Uploader.swf',
            server: '/api/common/upload/content',
            pick: {
                id: '#chooseFile',
                multiple: true
            },
            accept: {
                title: '图片文件',
                extensions: 'gif,jpg,jpeg,png',
                mimeTypes: 'image/jpg,image/jpeg,image/png'
            },
            auto: true,
            fileSingleSizeLimit: 1024 * 1024,

        });

        uploader.on('fileQueued', function (file) {
            console.log(file)
            vm.$data.files.push({
                name: file.name,
                status:'ready',
                progress: 0,
                webFileUrl: null
            });
        });

        uploader.on('uploadProgress', function (file, progress) {

            console.log('uploadProgress')
            console.log(file)
            console.log('progress:' + progress);

            var currentFile = findFile(file);
            currentFile.status = 'progress';
            currentFile.progress = progress*100;
        })
        uploader.on('uploadSuccess', function (file, response) {
            console.log('uploadSuccess')
            console.log(file)
            console.log(response)
            var currentFile = findFile(file);
            currentFile.status = 'success';
            currentFile.webFileUrl = response.webFileName;
            console.log(currentFile)
        })
        uploader.on('uploadError', function (file, reason) {
            console.log('uploadError')
            console.log(file)
            console.log(reason)

            var currentFile = findFile(file);
            currentFile.status = 'error';
            console.log(currentFile)
        });
        uploader.on('error', function (type) {
            console.log('error')
            console.log(type)

            let error = '';
            switch (type) {
                case 'F_DUPLICATE':
                    error = '选择的文件已存队列中';
                    break;
                case 'Q_TYPE_DENIED':
                    error = '选择的文件类型不正确';
                    break;
                case 'Q_EXCEED_SIZE_LIMIT':
                    error = '选择的文件大小超过设定值';
                    break;
                case 'Q_EXCEED_NUM_LIMIT':
                    error = '上传文件的队列超过设定值';
                default:
            }
            if (error) {
                $.alert(error);
            }
        })

        function removeFromQueue(file) {
            uploader.cancelFile(file);
        }

        function findFile(file) {
            let currentFile = {};
            $.each(vm.$data.files, function (i, item) {
                if (item.name == file.name) {
                    currentFile = item;
                    return;
                }
            });
            return currentFile;
        }

        function showUploadPanel(obj) {
            $(obj).next('div').toggle();
            uploader.refresh();
        }

        
    </script>
}